"""
服务网关API
提供基于自然语言的服务调用接口
"""

import inspect
import json
from typing import Dict, Any, Optional, List, Union
from pydantic import model_validator

from src.services.service_orchestrator import get_service_orchestrator
from src.services.service_executor import get_service_executor
from src.utils.logging import get_logger
def deep_clean_data(data: Any) -> Any:
    """
    深度清理数据，移除所有不可序列化的对象（如函数、类等）
    
    Args:
        data: 需要清理的数据
        
    Returns:
        清理后的数据
    """
    if isinstance(data, dict):
        cleaned = {}
        for key, value in data.items():
            # 确保键是字符串
            if not isinstance(key, str):
                key = str(key)
                
            # 递归清理值
            cleaned_value = deep_clean_data(value)
            if cleaned_value is not None:  # 只保留非None值
                cleaned[key] = cleaned_value
        return cleaned
    elif isinstance(data, (list, tuple)):
        return [deep_clean_data(item) for item in data if deep_clean_data(item) is not None]
    elif isinstance(data, (str, int, float, bool)) or data is None:
        return data
    elif callable(data):
        # 记录发现的可调用对象
        import logging
        logging.warning(f"发现可调用对象: {data}")
        return f"<function {getattr(data, '__name__', 'unnamed')}>"
    elif isinstance(data, type):
        # 记录发现的类型对象
        import logging
        logging.warning(f"发现类型对象: {data}")
        return f"<class {data.__name__}>"
    else:
        # 对于其他对象，尝试转换为字符串
        try:
            return str(data)
        except Exception as e:
            import logging
            logging.warning(f"无法序列化对象 {type(data)}: {e}")
            return f"<unserializable object {type(data).__name__}>"

# 延迟导入以避免依赖问题
def get_fastapi():
    try:
        from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, Body
        from fastapi.responses import JSONResponse
        return APIRouter, HTTPException, Depends, JSONResponse, BackgroundTasks, Body
    except ImportError:
        return None, None, None, None, None, None

def get_pydantic():
    try:
        from pydantic import BaseModel, Field
        return BaseModel, Field
    except ImportError:
        return None, None

def get_error_handler():
    try:
        from src.utils.decorators import handle_errors
        return handle_errors
    except ImportError:
        return None

# 获取依赖
APIRouter, _HTTPException, Depends, JSONResponse, BackgroundTasks, Body = get_fastapi()
BaseModel, Field = get_pydantic()
handle_errors = get_error_handler() or (lambda func=None: func if func else lambda f: f)  # 默认装饰器

# 检查必要的依赖是否导入成功
if APIRouter is None:
    raise ImportError("FastAPI is not installed. Please install it to use the service gateway.")
    
if BaseModel is None or Field is None:
    raise ImportError("Pydantic is not installed. Please install it to use the service gateway.")

# 确保HTTPException始终可用
class CustomHTTPException(Exception):
    """自定义HTTP异常类，兼容FastAPI的HTTPException"""
    def __init__(self, status_code: int, detail: Optional[str] = None):
        self.status_code = status_code
        self.detail = detail
        super().__init__(detail or "" if detail is not None else "")

if _HTTPException is not None:
    # 创建一个别名以避免类型冲突
    HTTPException = _HTTPException
else:
    HTTPException = CustomHTTPException

router = APIRouter(prefix="/services", tags=["services"])
logger = get_logger(__name__)


class ServiceRequest(BaseModel):
    """服务请求模型"""
    query: str = Field(..., description="自然语言查询", json_schema_extra={"example": "查询用户admin的信息"})
    user_id: Optional[int] = Field(None, description="用户ID")


class MultimodalServiceRequest(BaseModel):
    """多模态服务请求模型"""
    image_data: Optional[str] = Field(None, description="Base64编码的图像数据")
    voice_data: Optional[str] = Field(None, description="Base64编码的语音数据")
    user_id: Optional[int] = Field(None, description="用户ID")
    context: Optional[str] = Field(None, description="上下文信息")


class ServiceResponse(BaseModel):
    """服务响应模型"""
    success: bool = Field(..., description="是否成功")
    service_name: str = Field(..., description="调用的服务名称")
    result: Optional[Dict[str, Any]] = Field(None, description="服务执行结果")
    reasoning: str = Field(..., description="服务选择理由")
    processing_time: Optional[float] = Field(None, description="处理时间（秒）")
    
    @model_validator(mode='before')
    @classmethod
    def ensure_serializable(cls, data: Any) -> Any:
        """确保所有字段值都是可序列化的"""
        # 确保返回的是实际结果而不是协程对象
        import inspect
        import asyncio
        import logging
        
        # 检查并处理协程对象
        if inspect.iscoroutine(data) or inspect.isawaitable(data):
            # 在模型验证阶段不能直接await协程对象，记录警告并返回原始数据
            logging.warning("协程对象进入了ServiceResponse模型验证阶段，应在路由处理阶段处理")
            # 返回一个错误字典，而不是协程对象
            return {
                "success": False,
                "service_name": "unknown",
                "result": {"error": "协程对象未正确处理"},
                "reasoning": "协程对象未正确处理",
                "processing_time": 0.0
            }
        
        # 使用深度清理函数处理数据
        try:
            return deep_clean_data(data)
        except Exception:
            # 如果清理失败，直接返回数据
            return data
    
    class Config:
        # 确保模型可以处理任意类型并将其转换为JSON兼容类型
        arbitrary_types_allowed = True


class ServiceInfo(BaseModel):
    """服务信息模型"""
    name: str = Field(..., description="服务名称")
    description: str = Field(..., description="服务描述")
    parameters: Dict[str, Any] = Field(..., description="服务参数")
    keywords: List[str] = Field(..., description="服务关键词")
    examples: List[str] = Field(..., description="使用示例")
    version: str = Field(..., description="服务版本")
    
    @model_validator(mode='before')
    @classmethod
    def ensure_serializable(cls, data: Any) -> Any:
        """确保所有字段值都是可序列化的"""
        # 确保返回的是实际结果而不是协程对象
        import inspect
        import logging
        
        # 检查并处理协程对象
        if inspect.iscoroutine(data) or inspect.isawaitable(data):
            # 在模型验证阶段不能直接await协程对象，记录警告并返回原始数据
            logging.warning("协程对象进入了ServiceInfo模型验证阶段，应在路由处理阶段处理")
            # 返回一个错误字典，而不是协程对象
            return {
                "name": "unknown",
                "description": "协程对象未正确处理",
                "parameters": {},
                "keywords": [],
                "examples": [],
                "version": "1.0.0"
            }
            
        # 使用深度清理函数处理数据
        try:
            return deep_clean_data(data)
        except Exception as e:
            # 如果清理失败，记录错误并返回原始数据
            logging.warning(f"数据清理失败: {str(e)}")
            return data


class BatchServiceRequest(BaseModel):
    """批量服务请求模型"""
    requests: List[ServiceRequest] = Field(..., description="服务请求列表")


class BatchServiceResponse(BaseModel):
    """批量服务响应模型"""
    results: List[ServiceResponse] = Field(..., description="服务执行结果列表")
    processing_time: float = Field(..., description="总处理时间（秒）")
    
    @model_validator(mode='before')
    @classmethod
    def ensure_serializable(cls, data: Any) -> Any:
        """确保所有字段值都是可序列化的"""
        # 确保返回的是实际结果而不是协程对象
        import inspect
        import asyncio
        import logging
        
        # 检查并处理协程对象
        if inspect.iscoroutine(data) or inspect.isawaitable(data):
            # 在模型验证阶段不能直接await协程对象，记录警告并返回原始数据
            logging.warning("协程对象进入了BatchServiceResponse模型验证阶段，应在路由处理阶段处理")
            # 返回一个错误字典，而不是协程对象
            return {
                "results": [],
                "processing_time": 0.0
            }
        
        # 使用深度清理函数处理数据
        try:
            return deep_clean_data(data)
        except Exception:
            # 如果清理失败，直接返回数据
            return data


@router.post("/execute", response_model=ServiceResponse, summary="执行自然语言服务请求")
@handle_errors()
async def execute_natural_language_service(request: ServiceRequest):
    """
    基于自然语言描述执行服务请求
    
    - **query**: 自然语言查询，描述需要执行的服务
    - **user_id**: 可选的用户ID，用于权限验证
    
    示例:
    - "查询用户admin的信息" → 调用用户管理服务
    - "研究人工智能的发展趋势" → 调用研究服务
    - "创建一个系统故障的工单" → 调用票务服务
    """
    import time
    start_time = time.time()
    # 初始化service_name变量以避免在异常处理中未绑定
    service_name = "unknown"
    
    try:
        # 获取服务协调器和执行器
        orchestrator = get_service_orchestrator()
        executor = get_service_executor()
        
        # 分析查询并选择服务
        service_selection = await orchestrator.analyze_query(request.query)
        
        # 如果用户ID存在，使用智能决策选择最优服务
        if request.user_id is not None:
            try:
                # 获取智能决策服务
                from src.services.intelligent_decision_service import get_intelligent_decision_service
                intelligent_decision = get_intelligent_decision_service()
                
                # 构建上下文信息
                context = {
                    "query": request.query,
                    "current_time": time.time()
                }
                
                # 直接使用user_id，因为现在是int类型
                optimal_service = intelligent_decision.select_optimal_workflow(
                    request.user_id, request.query, context
                )
                
                # 如果智能决策返回了服务，使用智能决策的结果
                if optimal_service:
                    # 更新服务选择结果
                    original_service = service_selection.get("selected_service", "")
                    service_selection["selected_service"] = optimal_service
                    service_selection["reasoning"] = f"智能决策推荐: {optimal_service} (原始识别: {original_service})"
                    # 确保参数中包含问题参数
                    if "parameters" not in service_selection:
                        service_selection["parameters"] = {}
                    if optimal_service == "research_assistant" and "question" not in service_selection["parameters"]:
                        service_selection["parameters"]["question"] = request.query
            except Exception as e:
                logger.warning(f"智能决策服务调用失败: {str(e)}")
                # 继续使用原始服务选择结果
        
        if not service_selection:
            raise HTTPException(status_code=400, detail="无法识别查询意图")
            
        service_name = service_selection.get("selected_service")
        parameters = service_selection.get("parameters", {})
        reasoning = service_selection.get("reasoning", "")
        
        # 特殊处理research_assistant服务，确保包含question参数
        if service_name == "research_assistant" and "question" not in parameters:
            parameters["question"] = request.query
        
        # 验证服务名称是否存在
        if not service_name:
            raise HTTPException(status_code=400, detail="无法识别查询意图")
        
        # 验证服务是否存在
        if not executor.registry.service_exists(service_name):
            # 获取可用的服务列表，提供更好的错误提示
            available_services = list(executor.registry.list_services())
            service_list = ", ".join(available_services) if available_services else "无可用服务"
            error_detail = f"服务 '{service_name}' 不存在。可用的服务包括: {service_list}"
            
            # 即使在错误情况下也要返回正确的响应格式
            error_response = ServiceResponse(
                success=False,
                service_name=service_name or "unknown",
                result={"error": error_detail},
                reasoning=error_detail,
                processing_time=0.0
            )
            # 确保返回的是实际响应对象而不是协程
            import inspect
            while inspect.iscoroutine(error_response) or inspect.isawaitable(error_response):
                error_response = await error_response
            
            # 确保最终返回的是Response对象而不是协程
            while inspect.iscoroutine(error_response) or inspect.isawaitable(error_response):
                error_response = await error_response
                
            return error_response
        
        # 执行服务
        result = await executor.execute_service(service_name, parameters)
        # 确保返回的是实际结果而不是协程对象
        import asyncio
        import inspect
        while inspect.iscoroutine(result) or inspect.isawaitable(result):
            result = await result
        
        processing_time = time.time() - start_time
        
        # 确保正确处理返回结果
        formatted_result = result.get("data") if isinstance(result, dict) and "data" in result else result
        
        # 确保所有必需字段都有值，避免None值导致验证错误
        service_response = ServiceResponse(
            success=result.get("success", False) if isinstance(result, dict) else False,
            service_name=service_name or "",
            result=formatted_result,
            reasoning=reasoning or "服务执行完成",
            processing_time=processing_time
        )
        
        # 确保返回的是实际响应对象而不是协程
        if inspect.iscoroutine(service_response) or inspect.isawaitable(service_response):
            logger.warning("ServiceResponse是协程对象，尝试解析")
            try:
                service_response = await service_response
            except Exception as e:
                logger.error(f"解析ServiceResponse协程失败: {str(e)}")
                # 创建一个错误响应
                service_response = ServiceResponse(
                    success=False,
                    service_name=service_name or "",
                    result={"error": "服务执行结果解析失败"},
                    reasoning=f"服务执行结果解析失败: {str(e)}",
                    processing_time=processing_time
                )
            
        return service_response
    except Exception as e:
        logger.error(f"服务执行失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"服务执行失败: {str(e)}")


@router.post("/execute/batch", response_model=BatchServiceResponse, summary="批量执行自然语言服务请求")
@handle_errors()
async def execute_batch_services(request: BatchServiceRequest):
    """
    批量执行多个自然语言服务请求
    """
    import time
    start_time = time.time()
    
    results = []
    try:
        # 获取服务执行器
        executor = get_service_executor()
        orchestrator = get_service_orchestrator()
        
        # 依次执行每个请求
        for service_request in request.requests:
            try:
                # 分析查询并选择服务
                service_selection = await orchestrator.analyze_query(service_request.query)
                
                if not service_selection:
                    results.append(ServiceResponse(
                        success=False,
                        service_name="",
                        result={"error": "无法识别查询意图"},
                        reasoning="无法识别查询意图",
                        processing_time=0.0
                    ))
                    continue
                    
                service_name = service_selection.get("selected_service", "")
                parameters = service_selection.get("parameters", {})
                reasoning = service_selection.get("reasoning", "")
                
                # 验证服务是否存在
                if not executor.registry.service_exists(service_name):
                    # 获取可用的服务列表，提供更好的错误提示
                    available_services = list(executor.registry.list_services())
                    service_list = ", ".join(available_services) if available_services else "无可用服务"
                    error_detail = f"服务 '{service_name}' 不存在。可用的服务包括: {service_list}"
                    
                    results.append(ServiceResponse(
                        success=False,
                        service_name=service_name or "unknown",
                        result={"error": error_detail},
                        reasoning=error_detail,
                        processing_time=0.0
                    ))
                    continue
                
                # 执行服务
                result = await executor.execute_service(service_name, parameters)
                # 确保返回的是实际结果而不是协程对象
                import asyncio
                import inspect
                while inspect.iscoroutine(result) or inspect.isawaitable(result):
                    result = await result
                
                results.append(ServiceResponse(
                    success=result.get("success", False),
                    service_name=service_name,
                    result=result.get("data"),
                    reasoning=reasoning,
                    processing_time=time.time() - start_time  # 简化处理时间计算
                ))
            except Exception as e:
                logger.error(f"批量服务执行失败: {str(e)}", exc_info=True)
                results.append(ServiceResponse(
                    success=False,
                    service_name="",
                    result={"error": f"服务执行失败: {str(e)}"},
                    reasoning="",
                    processing_time=0.0
                ))
        
        total_processing_time = time.time() - start_time
        
        batch_response = BatchServiceResponse(
            results=results,
            processing_time=total_processing_time
        )
        
        # 确保返回的是实际响应对象而不是协程
        import inspect
        while inspect.iscoroutine(batch_response) or inspect.isawaitable(batch_response):
            batch_response = await batch_response
            
        # 最终确保返回的是Response对象而不是协程
        while inspect.iscoroutine(batch_response) or inspect.isawaitable(batch_response):
            batch_response = await batch_response
            
        return batch_response
    except Exception as e:
        logger.error(f"批量服务执行失败: {str(e)}", exc_info=True)
        # 返回统一的错误响应
        error_response = ServiceResponse(
            success=False,
            service_name="unknown",
            result={"error": f"批量服务执行失败: {str(e)}"},
            reasoning=f"批量服务执行失败: {str(e)}",
            processing_time=0.0
        )
        
        # 确保返回的是实际响应对象而不是协程
        import inspect
        while inspect.iscoroutine(error_response) or inspect.isawaitable(error_response):
            error_response = await error_response
            
        # 最终确保返回的是Response对象而不是协程
        while inspect.iscoroutine(error_response) or inspect.isawaitable(error_response):
            error_response = await error_response
            
        return error_response


@router.get("/list", response_model=List[ServiceInfo], summary="列出所有可用服务")
@handle_errors()
async def list_services():
    """
    列出所有已注册的服务及其信息
    """
    try:
        executor = get_service_executor()
        services = []
        
        # 获取所有注册的服务
        service_names = executor.registry.list_services()  # type: ignore
        for service_name in service_names:
            service_info = executor.registry.get_service_info(service_name)
            if service_info:
                services.append(ServiceInfo(
                    name=service_info['name'],
                    description=service_info['description'],
                    parameters=service_info['parameters'],
                    keywords=service_info['keywords'],
                    examples=service_info['examples'],
                    version=service_info['version']
                ))
        
        return services
    except Exception as e:
        logger.error(f"获取服务列表失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取服务列表失败: {str(e)}")


@router.get("/info/{service_name}", response_model=ServiceInfo, summary="获取特定服务信息")
@handle_errors()
async def get_service_info(service_name: str):
    """
    获取特定服务的详细信息
    """
    try:
        executor = get_service_executor()
        
        # 检查服务是否存在
        if not executor.registry.service_exists(service_name):
            raise HTTPException(status_code=404, detail=f"服务 '{service_name}' 不存在")
        
        # 获取服务信息
        service_info = executor.registry.get_service_info(service_name)
        if not service_info:
            raise HTTPException(status_code=404, detail=f"无法获取服务 '{service_name}' 的信息")
        
        return ServiceInfo(
            name=service_info['name'],
            description=service_info['description'],
            parameters=service_info['parameters'],
            keywords=service_info['keywords'],
            examples=service_info['examples'],
            version=service_info['version']
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取服务信息失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取服务信息失败: {str(e)}")


@router.post("/execute/{service_name}", response_model=ServiceResponse, summary="执行特定服务")
@handle_errors()
async def execute_specific_service(service_name: str, parameters: Optional[Dict[str, Any]] = None):
    """
    直接执行指定名称的服务
    
    - **service_name**: 要执行的服务名称
    - **parameters**: 服务所需的参数
    
    示例:
    - service_name: "user_management"
    - parameters: {"user_id": "admin"}
    """
    # 如果parameters为None，设置为空字典
    if parameters is None:
        parameters = {}
        
    import time
    start_time = time.time()
    
    # 初始化executor变量
    executor = get_service_executor()
    
    try:
        # 验证服务是否存在
        if not executor.registry.service_exists(service_name):
            # 获取可用的服务列表，提供更好的错误提示
            available_services = list(executor.registry.list_services())
            service_list = ", ".join(available_services) if available_services else "无可用服务"
            error_detail = f"服务 '{service_name}' 不存在。可用的服务包括: {service_list}"
            raise HTTPException(status_code=404, detail=error_detail)
        
        # 执行服务
        result = await executor.execute_service(service_name, parameters)
        # 确保返回的是实际结果而不是协程对象
        import asyncio
        import inspect
        while inspect.iscoroutine(result) or inspect.isawaitable(result):
            result = await result
        
        processing_time = time.time() - start_time
        
        # 确保返回的是可序列化的数据
        formatted_result = result
        if isinstance(result, dict):
            formatted_result = result.get("data", result)
        
        service_response = ServiceResponse(
            success=result.get("success", False) if isinstance(result, dict) else True,
            service_name=service_name,
            result=formatted_result,
            reasoning=f"直接调用服务: {service_name}",
            processing_time=processing_time
        )
        
        # 确保返回的是实际响应对象而不是协程
        while inspect.iscoroutine(service_response) or inspect.isawaitable(service_response):
            service_response = await service_response
            
        # 最终确保返回的是Response对象而不是协程
        while inspect.iscoroutine(service_response) or inspect.isawaitable(service_response):
            service_response = await service_response
            
        return service_response
        
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        processing_time = time.time() - start_time
        logger.error(f"服务执行失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"服务执行失败: {str(e)}")


@router.get("/health", summary="服务网关健康检查")
async def health_check():
    """服务网关健康状态检查"""
    import time
    try:
        # 检查核心组件是否正常
        orchestrator = get_service_orchestrator()
        executor = get_service_executor()
        
        # 获取服务数量
        services_count = len(executor.registry.get_all_services())
        
        # 获取服务健康状态
        health_status = executor.registry.get_all_health_status()
        
        # 获取缓存统计
        cache_stats = orchestrator.get_cache_stats()
        
        # 检查负载均衡器状态
        load_balancer_status = check_load_balancer_status()
        
        content = {
            "status": "healthy",
            "services_count": services_count,
            "services_health": health_status,
            "load_balancer_status": load_balancer_status,
            "orchestrator_available": orchestrator.llm is not None,
            "cache_stats": cache_stats,
            "timestamp": int(time.time() * 1000)  # 使用当前时间戳
        }
        
        # 使用JSONResponse如果可用，否则直接返回字典
        if JSONResponse is not None:
            response = JSONResponse(content=content)
            # 确保返回的是实际响应对象而不是协程
            import inspect
            while inspect.iscoroutine(response) or inspect.isawaitable(response):
                response = await response
            return response
        else:
            # 如果JSONResponse不可用，确保返回的是Response对象
            from starlette.responses import Response
            response = Response(content=json.dumps(content), media_type="application/json")
            # 确保返回的是实际响应对象而不是协程
            import inspect
            while inspect.iscoroutine(response) or inspect.isawaitable(response):
                response = await response
            return response
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"健康检查失败: {str(e)}")


def check_load_balancer_status():
    """检查负载均衡器状态"""
    # 这里应该实现实际的负载均衡器状态检查逻辑
    # 当前实现为占位符，实际项目中应该连接到负载均衡器系统
    return {
        "status": "active",
        "algorithm": "round_robin",
        "instances": [],
        "failover_enabled": True
    }


@router.get("/metrics", summary="服务网关指标")
async def get_metrics():
    """获取服务网关性能指标"""
    import time
    import json
    try:
        executor = get_service_executor()
        metrics = executor.registry.get_all_metrics()
        
        # 计算总体成功率
        total_executions = sum(m["total_executions"] for m in metrics.values())
        successful_executions = sum(m["successful_executions"] for m in metrics.values())
        success_rate = successful_executions / total_executions if total_executions > 0 else 0
        
        content = {
            "metrics": metrics,
            "summary": {
                "total_executions": total_executions,
                "successful_executions": successful_executions,
                "success_rate": f"{success_rate * 100:.2f}%"
            },
            "timestamp": int(time.time() * 1000)  # 使用当前时间戳
        }
        
        # 使用JSONResponse如果可用，否则直接返回字典
        if JSONResponse is not None:
            response = JSONResponse(content=content)
            # 确保返回的是实际响应对象而不是协程
            import inspect
            while inspect.iscoroutine(response) or inspect.isawaitable(response):
                response = await response
            return response
        else:
            # 如果JSONResponse不可用，确保返回的是Response对象
            from starlette.responses import Response
            response = Response(content=json.dumps(content), media_type="application/json")
            # 确保返回的是实际响应对象而不是协程
            import inspect
            while inspect.iscoroutine(response) or inspect.isawaitable(response):
                response = await response
            return response
    except Exception as e:
        logger.error(f"获取指标失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取指标失败: {str(e)}")


# 错误处理
@router.get("/error-examples", summary="获取服务错误示例")
async def get_error_examples():
    """获取各种服务调用可能出现的错误示例"""
    return {
        "service_not_found": {
            "error": "服务 'unknown_service' 不存在",
            "solution": "检查服务名称是否正确，或使用 /services/list 查看可用服务"
        },
        "parameter_missing": {
            "error": "缺少必要参数: user_id",
            "solution": "在请求中提供完整的参数"
        },
        "service_not_implemented": {
            "error": "服务 'user_management' 功能暂未实现", 
            "solution": "该服务正在开发中，请稍后再试"
        },
        "permission_denied": {
            "error": "服务 'user_management' 权限不足",
            "solution": "检查用户权限或联系管理员"
        },
        "timeout": {
            "error": "服务 'research_assistant' 执行超时",
            "solution": "请稍后重试或简化查询内容"
        }
    }


@router.get("/load-balancer-config", summary="获取负载均衡配置")
async def get_load_balancer_config():
    """获取负载均衡器配置信息"""
    return {
        "status": "active",
        "algorithm": "round_robin",
        "failover_enabled": True,
        "supported_algorithms": ["round_robin", "random", "least_connections"],
        "instances": {}
    }


@router.post("/execute/image", response_model=ServiceResponse, summary="基于图像的服务请求")
@handle_errors()
async def execute_image_service(request: MultimodalServiceRequest):
    """
    基于图像输入执行服务请求
    
    - **image_data**: Base64编码的图像数据
    - **user_id**: 可选的用户ID，用于权限验证
    - **context**: 可选的上下文信息
    """
    import time
    import base64
    start_time = time.time()
    # 初始化service_name变量
    service_name = "unknown"
    
    try:
        if not request.image_data:
            raise HTTPException(status_code=400, detail="图像数据不能为空")
        
        # 获取服务协调器和执行器
        orchestrator = get_service_orchestrator()
        executor = get_service_executor()
        
        # 处理图像数据
        try:
            # 尝试解码Base64数据以验证其有效性
            image_bytes = base64.b64decode(request.image_data)
            # 这里应该调用图像处理服务来分析图像内容
            # 为演示目的，我们使用占位符
            image_analysis_result = "图像内容分析结果占位符"
            query = f"根据图像内容执行操作: {image_analysis_result}"
        except Exception as e:
            logger.error(f"图像数据处理失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=400, detail="图像数据格式无效")
        
        # 分析查询并选择服务
        service_selection = await orchestrator.analyze_query(query)
        
        if not service_selection:
            raise HTTPException(status_code=400, detail="无法识别图像内容")
            
        service_name = service_selection.get("selected_service")
        parameters = service_selection.get("parameters", {})
        reasoning = service_selection.get("reasoning", "")
        
        # 验证服务名称是否存在
        if not service_name:
            raise HTTPException(status_code=400, detail="无法识别图像内容对应的服务")
        
        # 验证服务是否存在
        if not executor.registry.service_exists(service_name):
            # 获取可用的服务列表，提供更好的错误提示
            available_services = list(executor.registry.list_services())
            service_list = ", ".join(available_services) if available_services else "无可用服务"
            error_detail = f"服务 '{service_name}' 不存在。可用的服务包括: {service_list}"
                            
            # 即使在错误情况下也要返回正确的响应格式
            return ServiceResponse(
                success=False,
                service_name=service_name or "unknown",
                result={"error": error_detail},
                reasoning=error_detail,
                processing_time=0.0
            )
        
        # 执行服务
        result = await executor.execute_service(service_name, parameters)
        
        processing_time = time.time() - start_time
        
        # 确保正确处理返回结果
        formatted_result = result.get("data") if isinstance(result, dict) and "data" in result else result
        
        return ServiceResponse(
            success=result.get("success", False) if isinstance(result, dict) else False,
            service_name=service_name,
            result=formatted_result,
            reasoning=reasoning,
            processing_time=processing_time
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"图像服务执行失败: {str(e)}", exc_info=True)
        # 使用统一的错误响应格式
        return ServiceResponse(
            success=False,
            service_name=service_name or "unknown",
            result={"error": f"图像服务执行失败: {str(e)}"},
            reasoning=f"图像服务执行失败: {str(e)}",
            processing_time=0.0
        )


@router.post("/execute/voice", response_model=ServiceResponse, summary="基于语音的服务请求")
@handle_errors()
async def execute_voice_service(request: MultimodalServiceRequest):
    """
    基于语音输入执行服务请求
    
    - **voice_data**: Base64编码的语音数据
    - **user_id**: 可选的用户ID，用于权限验证
    - **context**: 可选的上下文信息
    """
    import time
    import base64
    start_time = time.time()
    # 初始化service_name变量
    service_name = "unknown"
    
    try:
        if not request.voice_data:
            raise HTTPException(status_code=400, detail="语音数据不能为空")
        
        # 获取服务协调器和执行器
        orchestrator = get_service_orchestrator()
        executor = get_service_executor()
        
        # 处理语音数据
        try:
            # 尝试解码Base64数据以验证其有效性
            voice_bytes = base64.b64decode(request.voice_data)
            # 这里应该调用语音识别服务将语音转换为文本
            # 为演示目的，我们使用占位符
            voice_to_text_result = "语音转文本结果占位符"
            query = voice_to_text_result
        except Exception as e:
            logger.error(f"语音数据处理失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=400, detail="语音数据格式无效")
        
        # 分析查询并选择服务
        service_selection = await orchestrator.analyze_query(query)
        
        if not service_selection:
            raise HTTPException(status_code=400, detail="无法识别语音内容")
            
        service_name = service_selection.get("selected_service")
        parameters = service_selection.get("parameters", {})
        reasoning = service_selection.get("reasoning", "")
        
        # 验证服务名称是否存在
        if not service_name:
            raise HTTPException(status_code=400, detail="无法识别语音内容对应的服务")
        
        # 验证服务是否存在
        if not executor.registry.service_exists(service_name):
            # 获取可用的服务列表，提供更好的错误提示
            available_services = list(executor.registry.list_services())
            service_list = ", ".join(available_services) if available_services else "无可用服务"
            error_detail = f"服务 '{service_name}' 不存在。可用的服务包括: {service_list}"
                            
            # 即使在错误情况下也要返回正确的响应格式
            return ServiceResponse(
                success=False,
                service_name=service_name or "unknown",
                result={"error": error_detail},
                reasoning=error_detail,
                processing_time=0.0
            )
        
        # 执行服务
        result = await executor.execute_service(service_name, parameters)
        
        processing_time = time.time() - start_time
        
        # 确保正确处理返回结果
        formatted_result = result.get("data") if isinstance(result, dict) and "data" in result else result
        
        return ServiceResponse(
            success=result.get("success", False) if isinstance(result, dict) else False,
            service_name=service_name,
            result=formatted_result,
            reasoning=reasoning,
            processing_time=processing_time
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"语音服务执行失败: {str(e)}", exc_info=True)
        # 使用统一的错误响应格式
        return ServiceResponse(
            success=False,
            service_name=service_name or "unknown",
            result={"error": f"语音服务执行失败: {str(e)}"},
            reasoning=f"语音服务执行失败: {str(e)}",
            processing_time=0.0
        )


# 导出
__all__ = ["router"]